package com.pata.utils
{
	/**
	 * @author  pata
	 */
	public class DataProvider
	{
		private var data:Array;
		public function DataProvider(value:Object = null)
		{
			if (value == null) {
				data = [];
			} else {
				data = getDataFromObject(value);				
			}
		}
		protected function getDataFromObject(obj:Object):Array {
			var retArr:Array;
			if (obj is Array) {
				var arr:Array = obj as Array;
				if (arr.length > 0) {
					if (arr[0] is String || arr[0] is Number) {
						retArr = [];
						// convert to object array.
						for (var i:uint = 0; i < arr.length; i++) {
							var o:Object = {label:String(arr[i]),data:arr[i]}
							retArr.push(o);
						}
						return retArr;
					}
				}
				return obj.concat();
			} else if (obj is DataProvider) {
				return obj.toArray();
			} else if (obj is XML) {
				var xml:XML = obj as XML;
				retArr = [];
				var nodes:XMLList = xml.*;
				for each (var node:XML in nodes) {
					var obj:Object = {};
					var attrs:XMLList = node.attributes();
					for each (var attr:XML in attrs) {
						obj[attr.localName()] = attr.toString();
					}
					var propNodes:XMLList = node.*;
					for each (var propNode:XML in propNodes) {
						if (propNode.hasSimpleContent()) {
							obj[propNode.localName()] = propNode.toString();
						}
					}
					retArr.push(obj);
				}
				return retArr;
			} else {
				throw new TypeError("Error: Type Coercion failed: cannot convert "+obj+" to Array or DataProvider.");
				return null;
			}
		}
		public function removeItemAt(index:int):void
		{
			data.splice(index, 1);
		}
		public function toArray():Array {
			return data.concat();
		}
		public function get length():uint {
			return data.length;
		}
		public function toString():String {
			return "DataProvider ["+data.join(" , ")+"]";
		}
	}
}